package testBusiness;

import com.alibaba.fastjson.JSONObject;
import models.MyConfig;

import java.lang.reflect.Method;

/**
 * Created by yangxianming on 2018/12/18.
 * "expect": {
        "left": "text",
        "sign": "==",
        "right": "设计稿",
        "type": "comparison"
 }

 返回： 0失败  1通过
 */
public class AnalysisScheduler {

    public String parse(MyConfig myConfig, JSONObject expect){
        //普通模式验证
        String actionName = "testBusiness.AnalysisScheduler";
        Class<?> action;
        try {
            action = Class.forName(actionName);
            Method method = action.getDeclaredMethod(expect.getString("type") + "Action", JSONObject.class);
            return (String)method.invoke(action.newInstance(), expect);
        } catch (Exception e) {
            e.printStackTrace();
            return "0";
        }
    }

    private String containAction(JSONObject expect) throws Exception {
        //{"type":"Contain"<,"list":>,"lift":"牛","sign":"->","right":"小牛"}   符号 -> <->
        String sign = expect.getString("sign");
        String left = expect.getString("left");
        String right = expect.getString("right");

        if (!left.contains(right) && sign.equals("->"))
            return "0";

        if (left.contains(right) && sign.equals("<->"))
            return "0";

        return "1";
    }

    private String comparisonAction(JSONObject expect) throws Exception {
        //{"type":"Comparison"<,"list":>,"left":"年后","sign":"==","right":"年后}"}
        // 符号 == != < > <= >=
        String sign = expect.getString("sign");
        String left = expect.getString("left");
        String right = expect.getString("right");

        if (sign.equals("!=") && left.equals(right))
            return "0";

        if (sign.equals("==") && !left.equals(right))
            return "0";

        if (sign.equals("<") || sign.equals("<=") || sign.equals(">") || sign.equals(">=")){
            Long a0, a1;
            try {
                a0 = Long.valueOf(left);
                a1 = Long.valueOf(right);
            }catch (Exception e){
                System.out.println("comparison value turn to int exception -" + left + " " + left);
                return "0";
            }
            if (!(a0 > a1) && sign.equals(">"))
                return "0";
            if (!(a0 < a1) && sign.equals("<"))
                return "0";
            if (!(a0 >= a1) && sign.equals(">="))
                return "0";
            if (!(a0 <= a1) && sign.equals("<="))
                return "0";

        }

        return "1";
    }
}
